package org.yate.oa.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.yate.oa.model.RestDayEntity;
import org.yate.oa.model.ResumeTaskEntity;
import org.yate.oa.model.UserEntity;
import org.yate.oa.service.IRestDayService;
import org.yate.oa.service.imp.OrgService;
import org.yate.oa.service.imp.RestDayService;
import org.yate.oa.service.imp.ResumeTaskService;
import org.yate.oa.service.imp.UserService;
import org.yate.oa.utils.LeaveType;
import org.yate.oa.utils.Pagination;
import org.yate.oa.utils.TaskType;

import com.alibaba.fastjson.JSONObject;

@WebServlet(urlPatterns = { "/leave/get", "/leave/post", "/leave/put", "/leave/delete" }, asyncSupported = true)
public class LeaveController extends BaseServletController {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		res.setCharacterEncoding("utf-8");
		req.setCharacterEncoding("utf-8");
		res.setContentType("text/html; charset=utf-8");
		String type = req.getParameter("type");
		if ("get".equals(type)) {
			getByUserId(req, res);
		} else if ("update".equals(type)) {
			updateByUserId(req, res);
		} else if ("all".equals(type)) {
			getAll(req, res);
		} else if ("cancel".equals(type)) {
			cancelLeave(req, res);
		} else if ("getCancels".equals(type)) {
			getCancels(req, res);
		} else if ("getUserLeave".endsWith(type)) {
			getUserLeave(req, res);
		} else if ("clear".equals(type)) {
			clearOldRestdays(req, res);
		}
	}

	/** 清空上个季度剩余的调休 **/
	protected void clearOldRestdays(HttpServletRequest req, HttpServletResponse res) throws IOException {
		// 仅保留当前季度剩余的调休天数
		PrintWriter out = res.getWriter();
		JSONObject json = new JSONObject();
		IRestDayService svr = this.springCtx.getBean(IRestDayService.class);
		Map<Integer, Double> currentQuaRestdays = new HashMap<Integer, Double>();
		int cMonth = Calendar.getInstance().get(Calendar.MONTH) + 1;
		if (cMonth < 3) {
			return;
		} else {
			cMonth -= cMonth % 3;
		}
		String[] strings = new String[] { Calendar.getInstance().get(Calendar.YEAR) + "-" + (cMonth - 2) + "-01 00:00:00",
				Calendar.getInstance().get(Calendar.YEAR) + "-" + (cMonth + 1) + "-01 00:00:00" };
		List<RestDayEntity> crdes = svr.getCurrentQuaRestdays(strings);
		String orgId = req.getParameter("orgId");
		orgId = StringUtils.isEmpty(orgId) ? "0" : orgId;
		List<Integer> ids = new ArrayList<Integer>();
		if (!orgId.equals("")) {
			OrgService orgService = this.springCtx.getBean(OrgService.class);
			ids.add(Integer.parseInt(orgId));
			PerformanceController.queryOrd(ids, Integer.parseInt(orgId), orgService);
		}
		List<RestDayEntity> rdes = svr.getEntitiesByUserIds(ids);
		for (RestDayEntity crde : crdes) {
			currentQuaRestdays.put(crde.getUserEntity().getId(), crde.getRestDay());
		}
		double tmpDays = 0;
		for (RestDayEntity rde : rdes) {
			if (rde.getRestDay() == 0) {
				continue;
			}
			tmpDays = currentQuaRestdays.get(rde.getUserEntity().getId()) == null ? 0 : currentQuaRestdays.get(rde.getUserEntity().getId());
			if (rde.getRestDay() > tmpDays) {
				rde.setRestDay(tmpDays);
				svr.update(rde);
			}
		}
		json.put("status", "200");
		json.put("msg", "clear rest days success.");
		out.print(json);
		out.flush();
		out.close();
	}

	protected void getUserLeave(HttpServletRequest req, HttpServletResponse res) throws IOException {
		PrintWriter out = res.getWriter();
		JSONObject json = new JSONObject();
		Integer userId = Integer.parseInt(req.getParameter("userId") == null ? "-1" : req.getParameter("userId"));
		if (userId > 0) {
			RestDayService restDayService = this.springCtx.getBean(RestDayService.class);
			RestDayEntity r = restDayService.getEntity(userId);
			if (r == null) {
				UserEntity ue = new UserEntity();
				ue.setId(userId);
				r = new RestDayEntity(ue, Double.valueOf("0"), Double.valueOf("0"));
				restDayService.add(r);
			}
			json.put("status", 200);
			json.put("data", r);
		} else {
			json.put("status", 201);
			json.put("text", "无此员工");
		}
		out.print(json);
		out.flush();
		out.close();
	}

	protected void getByUserId(HttpServletRequest req, HttpServletResponse res) throws IOException {
		PrintWriter out = res.getWriter();
		JSONObject json = new JSONObject();
		String trueName = req.getParameter("trueName");
		String orgId = req.getParameter("orgId");
		UserService userService = this.springCtx.getBean(UserService.class);
		String[] strings = { orgId, trueName };
		UserEntity u = userService.getEntityByUserName(strings);

		if (u != null) {
			RestDayService restDayService = this.springCtx.getBean(RestDayService.class);
			RestDayEntity r = restDayService.getEntity(u.getId());
			if (r != null) {
				json.put("status", 200);
				json.put("data", r);
			} else {
				json.put("status", 201);
				json.put("text", "没有此人的调休数据");
			}
		} else {
			json.put("status", 201);
			json.put("text", "该部门下无此员工");
		}
		out.print(json);
		out.flush();
		out.close();
	}

	protected void updateByUserId(HttpServletRequest req, HttpServletResponse res) throws IOException {
		PrintWriter out = res.getWriter();
		JSONObject json = new JSONObject();
		String userId = req.getParameter("userId");
		String leaveDay = req.getParameter("leaveDay");
		String restDay = req.getParameter("restDay");
		RestDayService restDayService = this.springCtx.getBean(RestDayService.class);
		RestDayEntity e = new RestDayEntity();
		e.setLeaveDay(Double.parseDouble(leaveDay));
		e.setRestDay(Double.parseDouble(restDay));
		UserEntity u = new UserEntity();
		u.setId(Integer.parseInt(userId));
		e.setUserEntity(u);
		restDayService.update(e);
		json.put("status", 200);
		out.print(json);
		out.flush();
		out.close();
	}

	protected void getAll(HttpServletRequest req, HttpServletResponse res) throws IOException {
		PrintWriter out = res.getWriter();
		JSONObject json = new JSONObject();
		String trueName = req.getParameter("trueName");
		String page = req.getParameter("page");
		int pageIndex = 0;
		if (!StringUtils.isEmpty(page)) {
			pageIndex = Integer.parseInt(page);
		}

		RestDayService restDayService = this.springCtx.getBean(RestDayService.class);

		Pagination<RestDayEntity> data = restDayService.getEntitieSearch(pageIndex, 10, null, null, trueName);
		json.put("status", 200);
		json.put("data", data);
		out.print(json);
		out.flush();
		out.close();
	}

	/**
	 * 销假
	 * 
	 * @param req
	 * @param res
	 * @throws IOException
	 */
	protected void cancelLeave(HttpServletRequest req, HttpServletResponse res) throws IOException {
		PrintWriter out = res.getWriter();
		JSONObject json = new JSONObject();
		int userId = Integer.parseInt(req.getParameter("userId"));
		Long beginDate = Long.parseLong(req.getParameter("beginDate"));
		String day = req.getParameter("day");
		String taskType = req.getParameter("taskType");
		UserEntity u = new UserEntity();
		ResumeTaskService resumeTaskService = this.springCtx.getBean(ResumeTaskService.class);
		ResumeTaskEntity r = new ResumeTaskEntity();
		r.setDays(Double.parseDouble(day));
		u.setId(userId);
		r.setProposer(u);
		r.setTaskType(taskType);
		r.setBeginDate(new Date(beginDate));
		resumeTaskService.add(r);

		// 销调休
		if (taskType.equals(TaskType.paidleave.name())) {
			RestDayService restDayService = this.springCtx.getBean(RestDayService.class);
			RestDayEntity restDayEntity = restDayService.getEntity(userId);
			double restDay = restDayEntity.getRestDay();
			double newDay = restDay + Double.parseDouble(day);
			restDayEntity = new RestDayEntity();
			u = new UserEntity();
			u.setId(userId);
			restDayEntity.setUserEntity(u);
			restDayEntity.setRestDay(newDay);
			restDayService.update(restDayEntity);
		}
		// 销年假
		if (taskType.equals(LeaveType.annual.name())) {
			RestDayService restDayService = this.springCtx.getBean(RestDayService.class);
			RestDayEntity restDayEntity = restDayService.getEntity(userId);
			double leaveDay = restDayEntity.getLeaveDay();
			double newDay = leaveDay + Double.parseDouble(day);
			restDayEntity = new RestDayEntity();
			u = new UserEntity();
			u.setId(userId);
			restDayEntity.setUserEntity(u);
			restDayEntity.setLeaveDay(newDay);
			restDayService.update(restDayEntity);
		}
		json.put("status", 200);
		out.print(json);
		out.flush();
		out.close();
	}

	/**
	 * 
	 * 展示所有销假记录
	 * 
	 * @param req
	 * @param res
	 * @throws IOException
	 */
	protected void getCancels(HttpServletRequest req, HttpServletResponse res) throws IOException {
		PrintWriter out = res.getWriter();
		JSONObject json = new JSONObject();
		String page = req.getParameter("page");
		String userName = req.getParameter("userName");
		int pageIndex = 0;
		if (!StringUtils.isEmpty(page)) {
			pageIndex = Integer.parseInt(page);
		}
		ResumeTaskService resumeTaskService = this.springCtx.getBean(ResumeTaskService.class);
		String[] strings = { userName };
		Pagination<ResumeTaskEntity> data = resumeTaskService.getEntitieSearch(pageIndex, 10, null, null, strings);
		json.put("status", 200);
		json.put("data", data);
		out.print(json);
		out.flush();
		out.close();
	}
}
